package com.cndw.kungfu.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.kungfu.comm.AccessFlag;
import com.cndw.kungfu.comm.JXSpreadTask;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsChat;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsDailyItem;
import com.cndw.kungfu.config.ConstantsDayIntKey;
import com.cndw.kungfu.config.ConstantsFlag;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.Livery;
import com.cndw.kungfu.domain.Monster;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Union;
import com.cndw.kungfu.ext.ConfigLangLib;
import com.cndw.kungfu.ext.LangUtil;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.NumberProcesser;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.DataSerialize;
import com.cndw.kungfu.model.battle.Battle;
import com.cndw.kungfu.model.battle.Fighter;
import com.cndw.kungfu.model.battle.Team;
import com.cndw.kungfu.model.goods.domain.SubPops;
import com.cndw.kungfu.model.goods.domain.SysModeAwards;
import com.cndw.kungfu.model.pvp.ChallengeManager;
import com.cndw.kungfu.model.pvp.LiveryManager;
import com.cndw.kungfu.model.pvp.OnlineExpAnimaWrest;
import com.cndw.kungfu.model.sys.ChatMain;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

@Controller
public class PvpController {
	@Autowired
	private ChallengeManager challengeManager;
	@Autowired
	private LiveryManager liveryManager;

	/**
	 * 获取英雄榜
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage getHeroList(Session session) {
		List<Map<String, Object>> heroListInfo = new LinkedList<Map<String, Object>>();
		List<Long> heroList = DataSerialize.getInstance().getChallengeData().getPlayers(1, 10);
		for (int i = 0; i < heroList.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			Player player = Context.getPlayerServer().getByPlayerId(heroList.get(i));
			map.put("playerId", player.getPlayerId());
			map.put("playerName", player.getPlayerName());
			map.put("level", player.getLevel());
			map.put("score", player.getScore());
			map.put("ranking", i + 1);
			heroListInfo.add(map);
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		QQDC.getInstance().logClick(player, LogFieldType.pvpHero);
		return ResponseMessage.getSuccMessage(heroListInfo);
	}

	/**
	 * 获取个人武林大会面板
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage show(Session session) {
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getLevel() < ConstantsLevel.lv25Challenge) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		Map<String, Object> map = new HashMap<String, Object>();
		int ranking = DataSerialize.getInstance().getChallengeData().getOrder(playerId);
		map.put("ranking", ranking);
		map.put("wining", player.getDataInfo().intDataGet(ConstantsIntKey.winning));
		int challengeCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.challengeCount);
		map.put("time", challengeCount > ConstantsModel.challengeNoCDNum ? player.getDataInfo().intDataGet(ConstantsIntKey.endTime) : 0);
		int buyCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.challengeBuy);
		int knightAddCount = 0;
		if (player.getKnight() != null) {// 武状元增加次数
			knightAddCount += player.getKnight().getPvpTimes();
		}
		map.put("num", ConstantsModel.challengeNum + buyCount + knightAddCount - challengeCount);
		map.put("buyNum", buyCount);
		map.put("nextAwardTime", DataSerialize.getInstance().getChallengeData().getNextAwardTime());
		map.put("pvpList", challengeManager.getEnmeys(playerId, ranking));
		SysModeAwards awards = SysModeAwards.get(challengeManager.getAwardsId(ranking, player.getLevel()));
		List<SubPops> subPopsList = awards != null ? awards.getSubPopsList() : null;
		map.put("awards", Context.getGoodsServer().makeAwards(subPopsList));

		int haveGot = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.tokenGot);
		int canGot = 0;
		if ((haveGot & Constants.tokenPvp2) > 0) {
			canGot = 2;
		} else if ((haveGot & Constants.tokenPvp1) > 0) {
			canGot = 1;
		}
		map.put("tokenCanGot", canGot);// 已领取武道令的状态

		QQDC.getInstance().logClick(player, LogFieldType.pvp);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 挑战
	 * 
	 * @param session
	 * @param eId
	 *            敌人playerId
	 * @return
	 */
	public ResponseMessage challenge(Session session, long eId, int enmeyRanking) {
		long playerId = session.getUid();
		boolean first = eId == ConstantsModel.challengeNpcPlayerId;
		int ranking = DataSerialize.getInstance().getChallengeData().getOrder(playerId);
		final Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getLevel() < ConstantsLevel.lv25Challenge) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.challenge.levellimit"));
		}
		if ((first && ranking > 0) || (!first && ranking <= 0)) {
			return null;
		}
		if (player.stateContains(Constants.playerState1024_aiUndercity)) {
			// return
			// ResponseMessage.ticpErrMsg(LanguageLib.get("undercity.ai.err"));
		}

		if (player.stateContains(Constants.playerState256_dart)) {// 押镖状态，不能进行
			return ResponseMessage.ticpErrMsg(LanguageLib.get("undercity.enter.dart"));
		}

		if (TimeProcesser.inTimePeriod(ConstantsModel.challengeForbidBegin, 86400) || TimeProcesser.inTimePeriod(0, ConstantsModel.challengeForbidEnd)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.challenge.forbid"));
		}
		Team team = player.getTeam();
		if (team != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.controlontem"));
		}
		int challengeCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.challengeCount);
		int addCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.challengeBuy);
		if (player.getKnight() != null) {// 武状元增加次数
			addCount += player.getKnight().getPvpTimes();
		}
		if (challengeCount >= (ConstantsModel.challengeNum + addCount)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.challenge.numlimit"));
		}
		int curTime = TimeProcesser.getUnixTime();
		if (curTime - player.getDataInfo().intDataGet(ConstantsIntKey.endTime) < ConstantsModel.challengeCdTime) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.challenge.cooltime"));
		}
		Set<Integer> enemyRanking = challengeManager.enemyRanking(ranking);
		int eRanking = DataSerialize.getInstance().getChallengeData().getOrder(eId);
		boolean challengeForward = ranking > eRanking;
		if (!first && !enemyRanking.contains(eRanking)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.challenge.wrongenmey"));
		}
		int noKill = Constants.playerState1_battle | Constants.playerState2_learn | Constants.playerState4_slaughter;
		if (player.stateContains(noKill)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.cooling"));
		}
		/*
		 * if(player.getDataInfo().getIntData(PlayerDataInfo.challengeEndTime) >
		 * curTime ||
		 * player.getDataInfo().getIntData(PlayerDataInfo.challengedEndTime) >
		 * curTime ||
		 * enmey.getDataInfo().getIntData(PlayerDataInfo.challengeEndTime) >
		 * curTime ||
		 * enmey.getDataInfo().getIntData(PlayerDataInfo.challengedEndTime) >
		 * curTime){ return
		 * ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.challenge.fight")); }
		 */
		// 敌人名次发生变化
		if (!first && eRanking != enmeyRanking) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.challenge.change"), 1);
		}
		int spendTime, challengeEndTime;
		boolean win = false;
		String eName;
		int eVId;
		Player enmey = null;
		Battle battle = null;
		if (first) {
			Monster monster = Context.getCacheCenter().getMonsterById(ConstantsModel.challengeNpcMId);
			eName = monster.getName();
			eVId = ConstantsModel.challengeNpcVId;
			battle = new Battle(player.getLikedFighter(), monster.fighter());
			battle.execBattle(Constants.battle_pvp);
			if (player.getDataInfo().intDataGet(ConstantsIntKey.aPetBag) == 1 && player.getDataInfo().getPet() != null) {
				player.getDataInfo().getPet().useBloodMagicBag();
				player.getDataInfo().commitSync();
			}
			battle.broadcast(player);
			win = battle.getWiner() == 1 ? true : false;
			player.useBloodMagicBag();
			if (win) {
				ranking = DataSerialize.getInstance().getChallengeData().addOrder(playerId);
			}
		} else {
			enmey = Context.getPlayerServer().getByPlayerId(eId);
			eName = enmey.getPlayerName();
			eVId = enmey.getVocationId();
			int[] hpMps = enmey.blodMagicMemory();

			battle = new Battle(player.getLikedFighter(), enmey.getLikedFighter());
			battle.execBattle(Constants.battle_pvp);

			battle.broadcast(player);
			win = battle.getWiner() == 1 ? true : false;
			player.useBloodMagicBagAndPet();// 自动使用气血包
			// 恢复被挑战方实际血量
			enmey.blodMagicMemoryRevert(hpMps);

			if (win && challengeForward) {
				DataSerialize.getInstance().getChallengeData().changeOrder(player.getPlayerId(), eId);
			}
		}
		spendTime = battle.getCostTime();
		challengeEndTime = curTime + spendTime;
		battle.clear();

		if (!first) {
			if (challengeCount >= ConstantsModel.challengeNoCDNum) {
				player.getDataInfo().intDataSet(ConstantsIntKey.endTime, challengeEndTime);
			}
			// enmey.getDataInfo().setIntData(PlayerDataInfo.challengedEndTime,
			// challengeEndTime);

			player.getDataInfo().getEveryDay().intDataAlter(ConstantsDayIntKey.challengeCount, 1);
			player.getDataInfo().commitSync();
		}
		String msg = null;
		String fMsg = null;
		int exp = 0;
		int asset = 0;
		String endTime = TimeProcesser.getDateByUnixTime(challengeEndTime);
		Map<String, Object> map = new HashMap<String, Object>();
		if (win) {
			exp = ConstantsModel.challengeAward[player.getLevel() - ConstantsLevel.lv25Challenge][0];
			asset = ConstantsModel.challengeAward[player.getLevel() - ConstantsLevel.lv25Challenge][1];
			int seqWin = player.getDataInfo().intDataGet(ConstantsIntKey.winning) + 1;
			player.getDataInfo().intDataSet(ConstantsIntKey.winning, seqWin);
			if (!first) {
				if (challengeForward) {
					fMsg = LanguageLib.get("pvp.challenge.suc", endTime, eId, eName, eVId, eName, eRanking);
					Context.getMessageServer().recordEvent(player.getPlayerId(), LanguageLib.get("pvp.challenge.title", eName), fMsg, Constants.eventTypePvp,
							spendTime);
					Context.getMessageServer().recordEvent(
							eId,
							LanguageLib.get("pvp.challenge.title", player.getPlayerName()),
							LanguageLib.get("pvp.challenge.failed", endTime, playerId, player.getPlayerName(), player.getVocationId(), player.getPlayerName(),
									ranking), Constants.eventTypePvp, spendTime);
				} else {
					fMsg = LanguageLib.get("pvp.challenge.suc2", endTime, eId, eName, eVId, eName);
					Context.getMessageServer().recordEvent(player.getPlayerId(), LanguageLib.get("pvp.challenge.title", eName), fMsg, Constants.eventTypePvp,
							spendTime);
				}
				enmey.getDataInfo().intDataSet(ConstantsIntKey.winning, 0);
				enmey.getDataInfo().commitSync();
				liveryManager.add(playerId, eId, 1);
			}
			ranking = DataSerialize.getInstance().getChallengeData().getOrder(playerId);
			if (seqWin >= 3) {
				msg = LanguageLib.get("pvp.challenge.seqwin", player.getPlayerName(), enmey.getPlayerName(), seqWin, ranking);
			}
			map.put("pvpList", challengeManager.getEnmeys(playerId, ranking));
		} else {
			exp = ConstantsModel.challengeAward[player.getLevel() - ConstantsLevel.lv25Challenge][0] * 8 / 10;
			asset = ConstantsModel.challengeAward[player.getLevel() - ConstantsLevel.lv25Challenge][1] * 8 / 10;
			player.getDataInfo().intDataSet(ConstantsIntKey.winning, 0);
			if (!first) {
				fMsg = LanguageLib.get("pvp.challenge.failed1", endTime, eId, eName, eVId, eName);
				Context.getMessageServer().recordEvent(player.getPlayerId(), LanguageLib.get("pvp.challenge.title", eName), fMsg, Constants.eventTypePvp,
						spendTime);
				if (challengeForward) {
					Context.getMessageServer().recordEvent(eId, LanguageLib.get("pvp.challenge.title", player.getPlayerName()),
							LanguageLib.get("pvp.challenge.suc1", endTime, playerId, player.getPlayerName(), player.getVocationId(), player.getPlayerName()),
							Constants.eventTypePvp, spendTime);
				}
				int seqWin = enmey.getDataInfo().intDataGet(ConstantsIntKey.winning) + 1;
				enmey.getDataInfo().intDataSet(ConstantsIntKey.winning, seqWin);
				enmey.getDataInfo().commitSync();
				if (seqWin >= 3) {
					msg = LanguageLib.get("pvp.challenge.seqwin", enmey.getPlayerName(), player.getPlayerName(), seqWin, DataSerialize.getInstance()
							.getChallengeData().getOrder(eId));
				}
				liveryManager.add(eId, playerId, 1);
			}
		}
		player.alterExp(exp);
		player.alterAsset(asset);
		player.commitSync();
		if (msg != null && !msg.equals("")) {
			ChatMain.systemMessageDelay(msg, spendTime + 3);
		}

		String notice = null;
		ranking = DataSerialize.getInstance().getChallengeData().getOrder(playerId);
		if (win) {
			if (first) {
				ChatMain.systemMessageDelay(LanguageLib.get("pvp.challenge.open", player.getPlayerName(), eName), spendTime + 5);
			} else {
				JXSpreadTask.complete(player, JXSpreadTask.pvp);
			}

			// 挑战第一名全服公告
			if (ranking == 1) {
				notice = LanguageLib.get("pvp.challenge.firstfailded", player.getPlayerName(), eName);
			} else if (!first) {
				notice = LanguageLib.get("pvp.challenge.win", player.getPlayerName(), eName, ranking);
			}
		} else {
			if (eRanking == 1) {
				notice = LanguageLib.get("pvp.challenge.firstsuc", eName, player.getPlayerName());
			} else if (!first) {
				notice = LanguageLib.get("pvp.challenge.failded", player.getPlayerName(), eRanking, eName);
			}
		}

		if (notice != null) {
			ChatMain.systemMessageDelay(notice, spendTime + 10);
		}

		// 加到每日奖励
		player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.WuLinConferenceSportsItem);
		map.put("asset", player.getAsset());
		map.put("exp", player.getExp());
		map.put("expGot", exp);
		map.put("assetGot", asset);
		SysModeAwards awards = SysModeAwards.get(challengeManager.getAwardsId(ranking, player.getLevel()));
		List<SubPops> subPopsList = awards != null ? awards.getSubPopsList() : null;
		map.put("awards", Context.getGoodsServer().makeAwards(subPopsList));

		map.put("endTime", challengeCount >= ConstantsModel.challengeNoCDNum ? player.getDataInfo().intDataGet(ConstantsIntKey.endTime) : 0);
		map.put("ranking", ranking);
		map.put("seqwin", player.getDataInfo().intDataGet(ConstantsIntKey.winning));
		if (fMsg != null) {
			map.put("msg", fMsg);
		}
		LogServer.recordLog(player, ConstantsLog.battle, 40011, eName, win, exp, asset);
		QQDC.getInstance().logClick(player, LogFieldType.battlepvp);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 消耗冷却时间
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage cancelChallengeCd(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int challengeEndTime = player.getDataInfo().intDataGet(ConstantsIntKey.endTime);
		if (challengeEndTime > TimeProcesser.getUnixTime()) {
			// return
			// ResponseMessage.getFailMessage(LanguageLib.get("comm.err.args"));
			return ResponseMessage.getFailMessage(false);
		}
		int time = ConstantsModel.challengeCdTime - (TimeProcesser.getUnixTime() - challengeEndTime);
		if (time <= 0) {
			// return
			// ResponseMessage.getFailMessage(LanguageLib.get("comm.err.args"));
			return ResponseMessage.getFailMessage(false);
		}

		int gold = NumberProcesser.ceil(time, 60);
		if (gold > player.getGoldAll()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		} else if (gold <= 0) {
			return null;
		}
		player.getDataInfo().intDataSet(ConstantsIntKey.endTime, challengeEndTime - time);
		player.getDataInfo().commitSync();
		player.alterGoldAll(-gold);
		player.commitSync();
		LogServer.recordLog(player, ConstantsLog.battle, 40012, gold);
		LogServer.costEventLog(player.getPlayerId(), gold, ConstantsCost.pvpCool);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 购买挑战次数
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage buyChallenge(Session session) {
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		int buyNum = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.challengeBuy);
		if (buyNum >= ConstantsModel.challengeBuyNum) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.buyChallenge.buylimit"));
		}

		if (player.getGoldAll() < ConstantsModel.challengeBuyPrice[buyNum]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		player.getDataInfo().getEveryDay().intDataAlter(ConstantsDayIntKey.challengeBuy, 1);
		player.getDataInfo().commitSync();
		player.alterGoldAll(-ConstantsModel.challengeBuyPrice[buyNum]);
		player.commitSync();
		LogServer.recordLog(player, ConstantsLog.battle, 40013, buyNum + 1, ConstantsModel.challengeBuyPrice[buyNum]);
		LogServer.costEventLog(playerId, ConstantsModel.challengeBuyPrice[buyNum], ConstantsCost.pvpTimes);

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("buyNum", buyNum + 1);
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		return ResponseMessage.getSuccMessage(map);
	}

	public ResponseMessage gotPvpToken(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int haveCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.challengeCount);
		int haveGot = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.tokenGot);
		int isGot = 0;
		boolean gotNoSign = (haveGot & Constants.tokenPvp1) <= 0;
		boolean gotNoSign2 = (haveGot & Constants.tokenPvp2) <= 0;
		if (haveCount >= ConstantsModel.tokenGotPvpNum[0] && gotNoSign) {
			isGot = Constants.tokenPvp1;
		} else if (haveCount >= ConstantsModel.tokenGotPvpNum[1] && gotNoSign2) {
			isGot = Constants.tokenPvp2;
		}
		if (!gotNoSign2) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.token.have"));
		}
		if (isGot == 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.token.notimes", gotNoSign ? ConstantsModel.tokenGotPvpNum[0]
					: ConstantsModel.tokenGotPvpNum[1]));
		}
		if (!player.getPlayerBoxs().checkBlack()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", 1));
		}
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(GoodsEffectConfig.warTokenGoodsId);
		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.tokenGot, haveGot | isGot);
		player.getDataInfo().commitSync();
		Context.getGoodsServer().giveGoodsBing(session.getUid(), GoodsEffectConfig.warTokenGoodsId, 1, 1);
		LogServer
				.recordLog(player, ConstantsLog.goods, 70022, 1, 1, player.getPlayerBoxs().getStackNum(GoodsEffectConfig.warTokenGoodsId), goodsMode.getName());

		return ResponseMessage.ticpMsg(LanguageLib.get("pvp.token.suc"));
	}

	/**
	 * 打开侍从面板
	 * 
	 * @param session
	 */
	public ResponseMessage showLivery(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv25Livery) {
			return null;
		}
		Livery livery = liveryManager.getFreashLivery(session.getUid());
		int cardId = livery.getCardId();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("cardId", cardId);
		if (cardId == 0 || cardId == 1) {// 自由身 老爷
			map.put("leaveCatch", ConstantsModel.liveryCatchLimit + player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lCatchBuy)
					- player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lCatch));
			map.put("leaveSave", ConstantsModel.liverySaveLimit - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lSave));
			map.put("catchBuy", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lCatchBuy));
			if (cardId == 1) {
				map.put("leaveInact", ConstantsModel.liveryInteractLimit - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lInAct));
				// map.put("inactTime",
				// player.getDataInfo().getIntData(PlayerDataInfo.liveryInactTime));
				map.put("exp", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lExp));
				map.put("maxExp", ConstantsModel.liveryMaxExp[player.getLevel() - ConstantsLevel.lv25Livery]);
			}
			if (TimeProcesser.getUnixTime() < player.getDataInfo().intDataGet(ConstantsIntKey.guardEnd)) {
				map.put("guardEnd", player.getDataInfo().intDataGet(ConstantsIntKey.guardEnd));
				map.put("guardName", Context.getUndercityServer().getMonster(player.getDataInfo().intDataGet(ConstantsIntKey.guardId)).getName());
			}
		} else if (cardId == 2) {// 侍从
			map.put("leaveCallHelp", ConstantsModel.liveryCallHelpLimit - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lhelp));
			map.put("leaveRevolt", ConstantsModel.liveryRevoltLimit + player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevoltBuy)
					- player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevolt));
			Player mPlayer = Context.getPlayerServer().getByPlayerId(livery.getMasterId());
			map.put("mId", mPlayer.getPlayerId());
			map.put("mName", mPlayer.getPlayerName());
			map.put("mLevel", mPlayer.getLevel());
			map.put("mVid", mPlayer.getVocationId());
			map.put("revoltBuy", player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevoltBuy));
			map.put("leaveInact", ConstantsModel.liveryInteractLimit - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lInAct));
			map.put("inactTime", player.getDataInfo().intDataGet(ConstantsIntKey.lInact));
		}

		// Context.getTaskServer().notifyToSpark(session.getUid(),
		// ConstantsTask.spark31Livery, 1);

		QQDC.getInstance().logClick(player, LogFieldType.livery);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 获取手下败将\夺仆之敌\求救列表\解救列表
	 * 
	 * @param session
	 * @param type
	 *            0手下败将 1夺仆之敌 2 求救列表 3解救列表4高手列表
	 * @return
	 */
	public ResponseMessage getKindsList(Session session, int type) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv25Livery) {
			return null;
		}
		Livery livery = liveryManager.getFreashLivery(session.getUid());
		Set<Long> ids = null;
		if (type == 0) {
			ids = livery.getLoserSet();
		} else if (type == 1) {
			ids = livery.getRobEnemySet();
		} else if (type == 2 || type == 3) {
			Union union = Context.getUnionServer().getUnionById(player.getUnionId());
			if (union != null) {
				ids = union.getMemberIds();
			}
		}
		List<Map<String, Object>> resultList = new LinkedList<Map<String, Object>>();
		if (ids != null) {
			for (long l : ids) {
				if (l != session.getUid()) {
					Player tp = Context.getPlayerServer().getByPlayerId(l);
					Livery tl = liveryManager.getFreashLivery(l);
					if (tl.getMasterId() == session.getUid() || livery.getMasterId() == tl.getPlayerId() || (type == 2 && tl.getCardId() == 2)
							|| (type == 3 && tl.getCardId() != 2)) {
						continue;
					}
					Map<String, Object> tm = new HashMap<String, Object>();
					tm.put("id", tp.getPlayerId());
					tm.put("name", tp.getPlayerName());
					tm.put("level", tp.getLevel());
					tm.put("cardId", tl.getCardId());
					tm.put("vId", tp.getVocationId());
					if (type == 0 || type == 1) {
						if (TimeProcesser.getUnixTime() < tp.getDataInfo().intDataGet(ConstantsIntKey.guardEnd)) {
							tm.put("guardEnd", tp.getDataInfo().intDataGet(ConstantsIntKey.guardEnd));
							tm.put("guardName", Context.getUndercityServer().getMonster(tp.getDataInfo().intDataGet(ConstantsIntKey.guardId)).getName());
						}
					}
					if (tl.getCardId() == 2) {
						Player mp = Context.getPlayerServer().getByPlayerId(tl.getMasterId());
						if (mp != null) {
							Union mu = Context.getUnionServer().getUnionById(mp.getUnionId());
							tm.put("mUName", mu != null ? mu.getName() : null);
							tm.put("mName", mp.getPlayerName());
						}
					}

					Union tu = Context.getUnionServer().getUnionById(tp.getUnionId());
					if (tu != null) {
						tm.put("uName", tu.getName());
					} else {
						tm.put("uName", null);
					}
					resultList.add(tm);
				}
			}
		} else {// 显示可雇佣高手列表
			if (type == 4) {
				int i = 0;
				for (int id : ConstantsModel.guardsId) {
					Monster monster = Context.getUndercityServer().getMonster(id);
					Map<String, Object> tm = new HashMap<String, Object>();
					tm.put("id", monster.getId());
					tm.put("name", monster.getName());
					tm.put("level", monster.getLevel());
					tm.put("icon", monster.getIcon());
					tm.put("gold", ConstantsModel.guardCost[i]);
					tm.put("guardTime", ConstantsModel.guardTime[i]);
					resultList.add(tm);
					i++;
				}
			}
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("type", type);
		map.put("list", resultList);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 抓侍从、求救、解救、反抗、夺仆
	 * 
	 * @param session
	 * @param objId
	 *            人物Id
	 * @param type
	 *            0抓侍从、1求救、2解救、3反抗 、4夺仆之敌
	 * @return
	 */
	public ResponseMessage liveryFight(Session session, long objId, int type) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv25Livery) {
			return null;
		}

		if (type < 0 || type > 4 || session.getUid() == objId) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		if (type != 1 && player.stateContains(Constants.playerState1024_aiUndercity)) {
			// return
			// ResponseMessage.ticpErrMsg(LanguageLib.get("undercity.ai.err"));
		}

		if (player.stateContains(Constants.playerState256_dart)) {// 押镖状态，不能进行
			return ResponseMessage.ticpErrMsg(LanguageLib.get("undercity.enter.dart"));
		}

		int noKill = Constants.playerState1_battle | Constants.playerState2_learn | Constants.playerState4_slaughter;
		if (type != 1 && player.stateContains(noKill)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.cooling"));
		}

		long f1 = session.getUid();
		long f2 = objId;
		boolean isProtected = false;
		Livery livery = liveryManager.getFreashLivery(session.getUid());
		Player objPlayer = Context.getPlayerServer().getByPlayerId(objId);
		if (type == 0) {// 抓侍从
			if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lCatch) >= player.getDataInfo().getEveryDay()
					.intDataGet(ConstantsDayIntKey.lCatchBuy)
					+ ConstantsModel.liveryCatchLimit) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.catchlimit"));
			}
			if (livery.getLiverySet().size() >= ConstantsModel.liveryHaveLimit) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.havelimit"));
			}
			Livery objLivery = liveryManager.getFreashLivery(objId);
			// 是否处于高手保护下
			if (objLivery.getCardId() == 0 && TimeProcesser.getUnixTime() < objPlayer.getDataInfo().intDataGet(ConstantsIntKey.guardEnd)) {
				isProtected = true;
			} else if (objLivery.getCardId() == 2) {
				f2 = objLivery.getMasterId();
			}

		} else if (type == 1) {// 求救
			if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lhelp) >= ConstantsModel.liveryCallHelpLimit) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.callhelplimit"));
			}
			f1 = objId;
			f2 = liveryManager.getFreashLivery(session.getUid()).getMasterId();
		} else if (type == 2) {// 解救
			if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lSave) >= ConstantsModel.liverySaveLimit) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.savelimit"));
			}
			f2 = liveryManager.getFreashLivery(objId).getMasterId();
		} else if (type == 3) {// 反抗
			if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevolt) >= player.getDataInfo().getEveryDay()
					.intDataGet(ConstantsDayIntKey.lRevoltBuy)
					+ ConstantsModel.liveryRevoltLimit) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.revoltlimit"));
			}
		} else if (type == 4) {// 夺仆
			if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lCatch) >= player.getDataInfo().getEveryDay()
					.intDataGet(ConstantsDayIntKey.lCatchBuy)
					+ ConstantsModel.liveryCatchLimit) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.catchlimit"));
			}
			if (livery.getLiverySet().size() >= ConstantsModel.liveryHaveLimit) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.havelimit"));
			}
			Livery objLivery = liveryManager.getFreashLivery(objId);
			// if (objLivery.getCardId() == 2) {
			// f2 = objLivery.getMasterId();
			// }
			if (objLivery.getCardId() == 0 && TimeProcesser.getUnixTime() < objPlayer.getDataInfo().intDataGet(ConstantsIntKey.guardEnd)) {
				isProtected = true;
			} else if (objLivery.getCardId() == 2) {
				f2 = objLivery.getMasterId();
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		boolean win = false;
		int costTime = 0;
		Player fp1 = Context.getPlayerServer().getByPlayerId(f1);

		Team team = fp1.getTeam();
		if (team != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.controlontem"));
		}

		Player fp2 = Context.getPlayerServer().getByPlayerId(f2);
		if (fp1 == null || fp2 == null) {
			return null;
		}
		synchronized (fp2) {
			if (!liveryManager.canFight(session.getUid(), objId, type)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.cant"));
			}

			Fighter f = null;
			int[] oldHpMps = null, oldHpMpsFp2 = null;
			if (fp1.getPlayerId() != session.getUid()) {
				oldHpMps = fp1.blodMagicMemory();
			}

			if (!isProtected) {
				oldHpMpsFp2 = fp2.blodMagicMemory();
				f = fp2.getLikedFighter();
			} else {
				Monster monster = Context.getUndercityServer().getMonster(objPlayer.getDataInfo().intDataGet(ConstantsIntKey.guardId));
				f = monster.fighter();
			}

			Battle battle = new Battle(fp1.getLikedFighter(), f);
			battle.execBattle(Constants.battle_livery);

			battle.broadcast(player);
			costTime = battle.getCostTime();
			win = battle.getWiner() == 1 ? true : false;
			battle.clear();

			if (fp1.getPlayerId() == session.getUid()) {
				fp1.useBloodMagicBagAndPet();
			} else {
				fp1.blodMagicMemoryRevert(oldHpMps);
				fp1.commitSync();
			}

			if (!isProtected) {
				fp2.blodMagicMemoryRevert(oldHpMpsFp2);
				fp2.commitSync();
			}

			map = liveryManager.dealFight(session.getUid(), objId, type, win, costTime);
			map.put("bloodBag", player.getBloodBag());
			map.put("magicBag", player.getMagicBag());

		}
		LogServer.recordLog(player, ConstantsLog.battle, 40203, type, objPlayer.getPlayerName(), win);

		QQDC.getInstance().logClick(player, LogFieldType.battlelivery);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 获取侍从信息
	 * 
	 * @param session
	 */
	public ResponseMessage getLiveries(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv25Livery) {
			return null;
		}

		Livery livery = liveryManager.getFreashLivery(session.getUid());
		if (livery.getCardId() != 1) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.cant"));
		}

		List<Map<String, Object>> liveries = new LinkedList<Map<String, Object>>();
		Set<Long> ids = livery.getLiverySet();
		if (ids != null) {
			int curTime = TimeProcesser.getUnixTime();
			for (long l : ids) {
				Livery tl = liveryManager.getFreashLivery(l);
				Map<String, Object> tm = new HashMap<String, Object>();
				Player tp = Context.getPlayerServer().getByPlayerId(tl.getPlayerId());
				tm.put("id", tp.getPlayerId());
				tm.put("name", tp.getPlayerName());
				tm.put("level", tp.getLevel());
				int leaveTime = tl.getEndTime() <= curTime ? 0 : tl.getEndTime() - curTime;
				tm.put("doTime", leaveTime);
				int workTime = 0;
				if (tl.getEndTime() > tl.getBeginTime()) {
					workTime = tl.getEndTime() <= curTime ? tl.getEndTime() - tl.getBeginTime() : curTime - tl.getBeginTime();
				}
				int exp = NumberProcesser.floor(workTime, 10)
						* ConstantsModel.liveryWorkExp[tp.getLevel() - ConstantsLevel.lv25Challenge < 0 ? 0 : tp.getLevel() - ConstantsLevel.lv25Challenge];
				tm.put("doExp", exp);
				if (player.getKnight() != null && player.getKnight().getLiveryExpR() > 0) {// 武状元加成
					tm.put("addRate", player.getKnight().getLiveryExpR());
				}
				tm.put("vId", tp.getVocationId());
				tm.put("inactTime", tp.getDataInfo().intDataGet(ConstantsIntKey.lMInact));
				liveries.add(tm);
			}
		}
		return ResponseMessage.getSuccMessage(liveries);
	}

	/**
	 * 收取侍从经验
	 * 
	 * @param session
	 * @param liveryId
	 *            侍从id
	 * @param type
	 *            0 提取 1 压榨 2 抽干
	 * @param exp提出的经验值
	 * @return map
	 */
	public ResponseMessage collectExp(Session session, long liveryId, int type) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv25Livery || type < 0 || type > 2) {
			return null;
		}
		Livery livery = liveryManager.getFreashLivery(session.getUid());
		Livery tl = liveryManager.getFreashLivery(liveryId);

		if (livery.getCardId() != 1 || tl.getCardId() != 2 || tl.getMasterId() != session.getUid()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.cant"));
		}

		int todayExp = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lExp);
		if (todayExp >= ConstantsModel.liveryMaxExp[player.getLevel() - ConstantsLevel.lv25Livery]) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.collect.max"));
		}

		int curTime = TimeProcesser.getUnixTime();
		int workTime = tl.getEndTime() < curTime ? tl.getEndTime() - tl.getBeginTime() : curTime - tl.getBeginTime();
		int leaveTime = tl.getEndTime() - curTime;

		if ((type == 0 && workTime <= 0) || ((type == 1 || type == 2) && leaveTime <= 0)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		int time = 0;
		if (type == 0) {
			time = workTime;
		} else if (type == 1) {
			time = leaveTime < 3600 ? leaveTime : 3600;
		} else if (type == 2) {
			time = leaveTime;
		}

		Player tp = Context.getPlayerServer().getByPlayerId(liveryId);
		int prizeIndex = tp.getLevel() - ConstantsLevel.lv25Challenge < 0 ? 0 : tp.getLevel() - ConstantsLevel.lv25Challenge;
		int exp = NumberProcesser.floor(time, 10) * ConstantsModel.liveryWorkExp[prizeIndex];

		if (exp <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.collect.noexp"));
		}

		if (todayExp + exp >= ConstantsModel.liveryMaxExp[player.getLevel() - ConstantsLevel.lv25Livery]) {
			exp = ConstantsModel.liveryMaxExp[player.getLevel() - ConstantsLevel.lv25Livery] - todayExp;
			time = NumberProcesser.ceil(exp, ConstantsModel.liveryWorkExp[prizeIndex]) * 10;
		}

		int cost = NumberProcesser.ceil(time, 3600) * ConstantsModel.liveryCollect1Hour;
		boolean costGold = false;
		if ((type == 1 || type == 2) && player.getGoldAll() < cost) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}

		if (type == 0) {
			tl.setBeginTime(tl.getBeginTime() + time);
			liveryManager.updateLivery(tl);
		} else if (type == 1 || type == 2) {
			tl.setEndTime(tl.getEndTime() - time);
			liveryManager.updateLivery(tl);
			if (cost < 0) {
				return null;
			}
			costGold = true;
			player.alterGoldAll(-cost);
		}

		if (player.getKnight() != null) {// 武状元加成
			int addRate = player.getKnight().getLiveryExpR();
			if (addRate > 0) {
				exp = NumberProcesser.percentClac(exp, addRate);
			}
		}
		player.getDataInfo().getEveryDay().intDataAlter(ConstantsDayIntKey.lExp, exp);
		player.getDataInfo().commitSync();
		player.alterExp(exp);
		player.commitSync();

		Map<String, Object> map = new HashMap<String, Object>();
		if (costGold) {

			LogServer.costEventLog(session.getUid(), cost, ConstantsCost.liveryCollect);
		}
		LogServer.recordLog(player, ConstantsLog.battle, 40016, tp.getPlayerName(), costGold ? cost : 0, exp);
		map.put("id", liveryId);
		map.put("exp", exp);
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		leaveTime = tl.getEndTime() <= curTime ? 0 : tl.getEndTime() - curTime;
		map.put("doTime", leaveTime);
		workTime = 0;
		if (tl.getEndTime() > tl.getBeginTime()) {
			workTime = tl.getEndTime() <= curTime ? tl.getEndTime() - tl.getBeginTime() : curTime - tl.getBeginTime();
		}

		map.put("doExp", NumberProcesser.floor(workTime, 10) * ConstantsModel.liveryWorkExp[prizeIndex]);
		map.put("maxExp", ConstantsModel.liveryMaxExp[player.getLevel() - ConstantsLevel.lv25Livery]);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 侍从系统互动
	 * 
	 * @param session
	 * @param objId
	 *            互动对象id
	 * @param type
	 *            0侍从跟老爷互动 1 老爷跟侍从互动
	 * @param inactType
	 *            互动方式
	 * @param 1 发点赏钱 2 温柔安慰 3 一起外出 4 赠送物品 5 甜言蜜语 6 去泡温泉 7 随意撒气 8 跑马拉松 9 去买东西 10
	 *        清理仓库 11 上街遛狗 12 应酬替身 13哄他睡觉 14称赞老爷 15爱心早餐 16打扫房间 17送他礼物 18 整理仓库
	 *        19神奇料理 20装鬼吓他 21窃取宝物 22神医治病 23诅咒娃娃 24 谎报消息
	 * @return 玩家最终经验值
	 */
	public ResponseMessage interact(Session session, long objId, int type, int inactType) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv25Livery) {
			return null;
		}

		if (type < 0 || type > 1 || inactType <= 0 || inactType > 24) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}

		Livery livery = liveryManager.getFreashLivery(session.getUid());
		Livery objLivery = liveryManager.getFreashLivery(objId);
		if ((type == 0 && (livery.getCardId() != 2 || livery.getMasterId() != objId))
				|| (type == 1 && (livery.getCardId() != 1 || objLivery.getCardId() != 2 || objLivery.getMasterId() != session.getUid()))) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.cant"));
		}

		if (player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lInAct) >= ConstantsModel.liveryInteractLimit) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.interact.limit"));
		}

		int curTime = TimeProcesser.getUnixTime();
		int cdTime = curTime - player.getDataInfo().intDataGet(ConstantsIntKey.lInact);
		Player objPlayer = Context.getPlayerServer().getByPlayerId(objId);
		if (type == 1) {
			cdTime = curTime - objPlayer.getDataInfo().intDataGet(ConstantsIntKey.lMInact);
		}
		if (cdTime < ConstantsModel.liveryInactCd) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.interact.cd"));
		}
		int exp = ConstantsModel.liveryInactExp[objPlayer.getLevel() - ConstantsLevel.lv25Challenge < 0 ? 0 : objPlayer.getLevel()
				- ConstantsLevel.lv25Challenge];
		player.alterExp(exp);
		player.commitSync();
		player.getDataInfo().getEveryDay().intDataAlter(ConstantsDayIntKey.lInAct, 1);
		if (type == 0) {
			player.getDataInfo().intDataSet(ConstantsIntKey.lInact, curTime);
		} else {
			objPlayer.getDataInfo().intDataSet(ConstantsIntKey.lMInact, curTime);
			objPlayer.getDataInfo().commitSync();
		}
		player.getDataInfo().commitSync();

		// 加入到每日奖励
		player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.interactionItem);

		String msg = LanguageLib.get("pvp.interact.type" + inactType, objPlayer.getPlayerId(), objPlayer.getPlayerName(), objPlayer.getVocationId());
		Map<String, Object> map = new HashMap<String, Object>();
		if (msg != null && !msg.equals("")) {
			Context.getMessageServer().recordEvent(session.getUid(), LanguageLib.get("pvp.livery.title"), msg, Constants.eventTypeLivery);
			map.put("msg", msg);
		}

		map.put("leaveInact", ConstantsModel.liveryInteractLimit - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lInAct));
		map.put("exp", exp);
		map.put("inactTime", curTime);
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 释放侍从
	 * 
	 * @param session
	 * @param liveryId
	 */
	public ResponseMessage release(Session session, long liveryId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv25Livery) {
			return null;
		}

		Livery livery = liveryManager.getFreashLivery(session.getUid());
		Livery tl = liveryManager.getFreashLivery(liveryId);
		if (livery.getCardId() != 1 || tl.getCardId() != 2 || tl.getMasterId() != session.getUid()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.cant"));
		}

		liveryManager.remove(session.getUid(), liveryId, 0);
		Player tp = Context.getPlayerServer().getByPlayerId(liveryId);
		String msg = LanguageLib.get("pvp.release.master", tp.getPlayerId(), tp.getPlayerName(), tp.getVocationId());
		Context.getMessageServer().recordEvent(session.getUid(), LanguageLib.get("pvp.livery.title"), msg, Constants.eventTypeLivery);
		Context.getMessageServer().recordEvent(tp.getPlayerId(), LanguageLib.get("pvp.livery.title"),
				LanguageLib.get("pvp.release.livery", player.getPlayerId(), player.getPlayerName(), player.getVocationId()), Constants.eventTypeLivery);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", liveryId);
		map.put("msg", msg);
		map.put("cardId", livery.getCardId());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 购买抓捕、反抗次数
	 * 
	 * @param session
	 * @param type
	 *            0抓捕 1反抗
	 * @return 最终剩余次数
	 */
	public ResponseMessage buyNum(Session session, int type) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player.getLevel() < ConstantsLevel.lv25Livery || (type < 0 || type > 1)) {
			return null;
		}
		/*
		 * Livery livery = liveryManager.getLivery(session.getUid()); if((type
		 * == 0 && (livery.getCardId() != 0 || livery.getCardId() != 1)) ||
		 * (type == 1 && livery.getCardId() != 2)){ return
		 * ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args")); }
		 */

		int buyCount = 0;
		if (type == 0) {
			buyCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lCatchBuy);
		} else if (type == 1) {
			buyCount = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevoltBuy);
		}

		if (buyCount >= ConstantsModel.liveryBuy.length) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.buyChallenge.buylimit"));
		}

		int cost = ConstantsModel.liveryBuy[buyCount];
		if (player.getGoldAll() < cost) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}

		player.alterGoldAll(-cost);
		player.commitSync();
		Map<String, Object> map = new HashMap<String, Object>();
		if (type == 0) {
			player.getDataInfo().getEveryDay().intDataAlter(ConstantsDayIntKey.lCatchBuy, 1);
			map.put("leaveCatch", ConstantsModel.liveryCatchLimit + player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lCatchBuy)
					- player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lCatch));
		} else if (type == 1) {
			player.getDataInfo().getEveryDay().intDataAlter(ConstantsDayIntKey.lRevoltBuy, 1);
			map.put("leaveRevolt", ConstantsModel.liveryRevoltLimit + player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevoltBuy)
					- player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.lRevolt));
		}
		player.getDataInfo().commitSync();
		LogServer.recordLog(player, ConstantsLog.battle, 40015, buyCount + 1, type, cost);
		LogServer.costEventLog(session.getUid(), cost, ConstantsCost.liveryNum);
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 灵气位置抢夺
	 * 
	 * @param session
	 * @param type
	 * @param index
	 * @param playerId
	 * @return ResponseMessage
	 * @author Skycat
	 */
	@AccessFlag(ConstantsFlag.anima)
	public ResponseMessage animaWrest(Session session, int type, int index, int playerId) {
		if (type < 1 || type > 3) {
			return null;
		}

		int idx = 1;
		if (1 == type) {
			if (index < 1 || index > 5) {
				return null;
			}
			idx = index;
		} else if (2 == type) {
			if (index < 1 || index > 15) {
				return null;
			}
			idx = index + 5;
		} else if (3 == type) {
			if (index < 1 || index > 30) {
				return null;
			}
			idx = index + 20;
		}

		// 时间限制
		int currentTime = TimeProcesser.getUnixTime(); // 当前时间
		int begin = TimeProcesser.getHourTime("14:00"); // 灵气抢夺开始时间
		int end = TimeProcesser.getHourTime("16:00"); // 灵气抢夺结束时间
		if (currentTime < begin || currentTime > end) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("general.onlineExp.time"));
		}

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		long targetPlayerId = OnlineExpAnimaWrest.getPlayerIdByIndex(idx); // 目标位置玩家
		int exp = 0;
		int nowTime = 0;
		if (playerId != targetPlayerId) {
			// return ResponseMessage.ticpErrMsg("", 444);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("s", 2);
			return ResponseMessage.getSuccMessage(map); // 列表已变化,前端刷新列表
		}
		if (targetPlayerId == -1) { // 该位置没有玩家, 直接占有
			// 获取已打坐获得经验
			exp = Context.getGeneralServer().getOnlineExp(player);
			player.getDataInfo().intDataSet(ConstantsIntKey.beginDaZuo, TimeProcesser.getUnixTime());
			if (exp > 0) {
				player.commitSync();
			}
		} else {
			// 与该位置玩家pk
			Player targetPlayer = Context.getPlayerServer().getByPlayerId(targetPlayerId);
			if (targetPlayerId == session.getUid()) { // 不能自己占自己位置
				return null;
			}

			// cd时间
			nowTime = TimeProcesser.getUnixTime();
			int interval = nowTime - player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.expAnima);
			if (interval < ConstantsModel.animaWrestCdTime) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("general.onlineExp.cdTime", (ConstantsModel.animaWrestCdTime - interval)));
			}

			// PK 调用
			int[] hpMp1 = player.blodMagicMemory();
			int[] hpMp2 = targetPlayer.blodMagicMemory();

			Battle battle = new Battle(player.getLikedFighter(), targetPlayer.getLikedFighter());
			battle.execBattle(Constants.battle_pvp);
			boolean win = battle.getWiner() == 1 ? true : false;
			battle.broadcast(player); // 战报
			battle.clear();

			targetPlayer.blodMagicMemoryRevert(hpMp2);
			player.blodMagicMemoryRevert(hpMp1);

			// 更新抢夺时间
			player.getDataInfo().getEveryDay().intDataRemove(ConstantsDayIntKey.expAnima);
			player.getDataInfo().getEveryDay().intDataAlter(ConstantsDayIntKey.expAnima, nowTime);

			// 战斗结果
			if (!win) {
				return null; // 抢夺失败,不给提示
			}

			// 获取失败玩家已打坐经验
			int targetPlayerExp = Context.getGeneralServer().getOnlineExp(targetPlayer);
			if (targetPlayerExp > 0) {
				targetPlayer.commitSync();
			}

			// 获取当前玩家已打坐获得经验
			exp = Context.getGeneralServer().getOnlineExp(player);
			player.getDataInfo().intDataSet(ConstantsIntKey.beginDaZuo, TimeProcesser.getUnixTime());
			if (exp > 0) {
				player.commitSync();
			}

			// 发送灵气抢夺事件通知 以及失败玩家的获得的经验
			EventNotice notice = new EventNotice(ConstantsRadio.exp, ConstantsRadio.expOnline);
			notice.put("exp", exp); // 获得经验
			notice.put("playerName", player.getPlayerName()); // 抢夺玩家
			notice.put("type", type); // 灵气加成类型
			notice.broadcast(targetPlayer.getPlayerId());

			// 发送频道广播
			String message = LanguageLib.get("general.onlineExp.broadMsg", LangUtil.makeNameLink(player), LangUtil.makeNameLink(targetPlayer),
					ConfigLangLib.getConfigIndex("config.anima.name", type - 1), OnlineExpAnimaWrest.getAddRate(type),
					LangUtil.getColor(ConstantsModel.animaColor[type]), LangUtil.getColor(ConstantsModel.animaColor[type]));
			ChatMain.hearsayMessage(message, ConstantsChat.cwAnima);
		}

		// 是否已占有其他位置
		int oldIdx = OnlineExpAnimaWrest.isAnimalStatus(player.getPlayerId());
		if (oldIdx > 0) {
			OnlineExpAnimaWrest.remove(oldIdx);
		}

		// 获胜者加入抢夺列表覆盖原位置玩家
		OnlineExpAnimaWrest.add(idx, player.getPlayerId());

		// 占位或抢夺成功需要广播,更新抢占列表
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("exp", exp);
		map.put("s", 1); // 成功标识
		map.put("oldIdx", OnlineExpAnimaWrest.getClientIndex(oldIdx)); // 原位置
		map.put("newIdx", index); // 新位置
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 雇佣高手
	 * 
	 * @param session
	 * @param guardId
	 *            雇佣的高手id
	 * @param type
	 * @return
	 * @author Everest
	 */
	public ResponseMessage hireGuard(Session session, int guardId, int type) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		if (player == null || player.getLevel() < ConstantsLevel.lv25Livery) {
			return null;
		}
		if (player.stateContains(Constants.playerState256_dart)) {// 押镖状态，不能进行
			return ResponseMessage.ticpErrMsg(LanguageLib.get("undercity.enter.dart"));
		}

		int noKill = Constants.playerState1_battle | Constants.playerState2_learn | Constants.playerState4_slaughter;
		if (player.stateContains(noKill)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.cooling"));
		}

		// 当前处于高手保护状态
		if (TimeProcesser.getUnixTime() < player.getDataInfo().intDataGet(ConstantsIntKey.guardEnd)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.hireguard.protected"));
		}

		Monster monster = Context.getUndercityServer().getMonster(guardId);
		if (monster == null) {
			return null;
		}

		int index = 0;
		for (int i = 0; i < ConstantsModel.guardsId.length; i++) {
			if (ConstantsModel.guardsId[i] == guardId) {
				index = i;
			}
		}

		int costGold = ConstantsModel.guardCost[index];
		if (player.getGoldAll() < costGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}

		Livery livery = liveryManager.getFreashLivery(session.getUid());
		Player masterPlayer = Context.getPlayerServer().getByPlayerId(livery.getMasterId());

		Map<String, Object> map = new HashMap<String, Object>();
		boolean win = false;
		int costTime = 0;

		synchronized (masterPlayer) {
			if (!liveryManager.canFight(session.getUid(), masterPlayer.getPlayerId(), type)) {
				return ResponseMessage.ticpErrMsg(LanguageLib.get("pvp.liveryfight.cant"));
			}

			int[] hpMps = masterPlayer.blodMagicMemory();
			Battle battle = new Battle(monster.fighter(), masterPlayer.getLikedFighter());
			battle.execBattle(Constants.battle_livery);

			battle.broadcast(player);
			costTime = battle.getCostTime();
			win = battle.getWiner() == 1 ? true : false;
			battle.clear();
			// 还原状态
			masterPlayer.blodMagicMemoryRevert(hpMps);

			if (win) {
				player.getDataInfo().intDataSet(ConstantsIntKey.guardId, guardId);
				player.getDataInfo().intDataSet(ConstantsIntKey.guardEnd, TimeProcesser.getUnixTime() + ConstantsModel.guardTime[index]);
			}
			player.getDataInfo().commitSync();
			masterPlayer.getDataInfo().commitSync();
			masterPlayer.commitSync();
			map = liveryManager.dealFight(session.getUid(), masterPlayer.getPlayerId(), type, win, costTime);
		}

		player.alterGoldAll(-costGold);
		player.commitSync();
		LogServer.costEventLog(session.getUid(), costGold, ConstantsCost.hireGuard);
		LogServer.recordLog(player, ConstantsLog.battle, 40202, monster.getName(), costGold);
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("guardEnd", player.getDataInfo().intDataGet(ConstantsIntKey.guardEnd));
		map.put("guardName", Context.getUndercityServer().getMonster(player.getDataInfo().intDataGet(ConstantsIntKey.guardId)));
		return ResponseMessage.getSuccMessage(map);
	}
}